package edu.utd.text.game.designer.commands;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Scanner;

import edu.utd.text.game.designer.controller.DesignerController;
import edu.utd.text.game.domain.GameMap;

public class SaveCommand implements DesignerCommand {
	private String filename = "game.map";
	
	
	public String execute() throws Exception {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter a save file name (default: \"" 
				+ this.filename + "\"):");
		String userFilename = scanner.nextLine().trim();
		if (userFilename.equals("") || userFilename.isEmpty()) {
			userFilename = this.filename; //if no input, use default
		}
		this.filename = userFilename;
		System.out.println("Saving current game map...");
		
		String outcome = doSave();
		return outcome;
	}
	
	private String doSave() {
		GameMap map = DesignerController.INSTANCE.getGameMap();		
		
		FileOutputStream fos;
		ObjectOutputStream out;
		
		try {
			fos = new FileOutputStream(this.filename);
			out = new ObjectOutputStream(fos);
			System.out.println("Writing save file: \"" + this.filename + "\"");
			out.writeObject(map);
			out.close();
		} catch (IOException iox) {
			iox.printStackTrace();
			return "Error writing save file to disk.  Sorry.";
		}
		return "Save complete.";

	}

}
